package com.atguigu.tingshu.user.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.login.LoginCheck;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.catalina.User;
import org.bouncycastle.crypto.Mac;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private KafkaService kafkaService;

    @Autowired
    private RedisTemplate redisTemplate;




    //http://127.0.0.1/api/user/wxLogin/wxLogin/0d3MHSml2D
    //http://127.0.0.1:8500/api/user/wxLogin/wxLogin/0a3HU8ll2gpd7e4SZ0ml2Us2GR3HU8lD
    @Operation(summary = "小程序授权登录")
    @GetMapping("/wxLogin/{code}")
    public Result wxLogin(@PathVariable String code) throws WxErrorException {
        System.out.println(code);
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        String openId = sessionInfo.getOpenid();
        System.out.println(openId);
        //通过openId查询用户信息表
        UserInfo userInfo = userInfoService.lambdaQuery()
                .eq(UserInfo::getWxOpenId, openId)
                .one();
        //如果为空则没有登录
        if (null == userInfo) {
            //自动注册
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openId);
            userInfo.setNickname("ts" + UUID.randomUUID());
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            //插入数据
            userInfoService.save(userInfo);

            //发送消息 初始化用户账户
            kafkaService.sendMsg(KafkaConstant.QUEUE_USER_REGISTER,userInfo.getId().toString());
        }

        //如果已经注册，则将登录信息放入redis
        String token = UUID.randomUUID().toString();
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.opsForValue().set(key,userInfo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        //返回token
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    //http://127.0.0.1/api/user/wxLogin/getUserInfo
    @Operation(summary = "获取用户信息")
    @GetMapping("/getUserInfo")
    @LoginCheck
    public Result getUserInfo() {
        UserInfo userInfo = this.userInfoService.getUserInfo();
        return Result.ok(userInfo);
    }


    //http://127.0.0.1:8500/api/user/wxLogin/updateUser
    @Operation(summary = "修改用户信息")
    @PostMapping("/updateUser")
    @LoginCheck
    public Result updateUser(@RequestBody UserInfoVo userInfoVo) {
        log.info("修改用户信息:{}", userInfoVo);
        userInfoService.updateUser(userInfoVo);
        return Result.ok();
    }
}
